package com.example.lotteryticketdev.task;

import com.example.lotteryticketdev.config.SpringMailComponent;
import com.example.lotteryticketdev.entity.LuckyBall;
import com.example.lotteryticketdev.service.AttemptRequestService;
import com.example.lotteryticketdev.service.LuckyBallService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SpiderTask {

    @Autowired
    private AttemptRequestService attemptRequestService;
    @Autowired
    private LuckyBallService luckyBallService;
    @Autowired
    private SpringMailComponent springMailComponent;
    //MON TUE WED THU FRI SAT SUN
    //秒、分、时、日、月、周、年
    @Scheduled(cron = "0 30 23 ? * TUE,THU,SUN")
    public void test(){
        //找到数据库最新一条数据
        LuckyBall dbBall = luckyBallService.findMaxCodeLuckyBall();
        //请求最新数据（30条）
        int i = 1 ;
        boolean isInterrupt = false ;
        int end = -1 ;
        //精确插入的集合
        List<LuckyBall> temp = new ArrayList<>();
        List<LuckyBall> insert = new ArrayList<>();
        //指定只能请求 3 次 , 3次请求都没发现重复值(30,60,90),直接清除数据库所有数据重新爬取。
        while (i < 4){
            List<List<LuckyBall>> luckyBalls = attemptRequestService.getDataByBounds(i);
            for (List<LuckyBall> balls : luckyBalls) {
                if (balls.contains(dbBall)){
                    temp = balls ;
                    end = balls.indexOf(dbBall);
                    isInterrupt = true;
                    System.out.println("确定包含...");
                    break;
                }
            }
            if (isInterrupt){
                break;
            }
            System.out.println("第  "+ i +" 轮请求结束");
            i++;
        }
        //挑选截取缺少的部分
        StringBuilder sb = new StringBuilder();
        sb.append("今日新增");
        sb.append(end);
        sb.append("条数据，分别为：");
        for (int j = 0; j < end; j++) {
            LuckyBall luckyBall = temp.get(j);
            insert.add(luckyBall);
            sb.append("\n");
            sb.append("红球："+luckyBall.getRed()+" 蓝球："+luckyBall.getBlue());
            sb.append("\n");
        }
        luckyBallService.saveLuckyBall(insert);
        springMailComponent.send("","",sb.toString());
        springMailComponent.send("839934342@qq.com","",sb.toString());
    }
}
